<template>
	<el-drawer v-model="visible" title="菜单配置" :z-index="1999">
		<section class="content">
			<el-tree
				ref="treeRef"
				:data="dataSource"
				:props="{ label: 'title' }"
				node-key="id"
				show-checkbox
				check-strictly
				default-expand-all
			/>
			<el-button type="primary" @click="setMenu">确定</el-button>
		</section>
	</el-drawer>
</template>

<script setup>
import { computed, onMounted, ref, watch } from 'vue'
import {
	getBaseMenuTreeApi,
	getMenuAuthorityApi,
	addMenuAuthorityApi,
} from '@/api/api.js'
import { ElMessage } from 'element-plus'
import useAdminStore from '@/store/index.js'

const adminStore = useAdminStore()

const props = defineProps({
	visible: {
		type: Boolean,
		default: false,
	},
	id: {
		type: Number,
		default: 0,
	},
})
const emit = defineEmits(['update:visible'])
const dataSource = ref([])
const treeRef = ref()

const visible = computed({
	get: () => props.visible,
	set: (val) => {
		emit('update:visible', val)
	},
})

watch(
	() => props.id,
	async (id) => {
		if (id) {
			let res = await getMenuAuthorityApi({ authorityId: id })
			let data = []
			res.menus &&
				res.menus.forEach((item) => {
					data.push(item.id)
				})
			treeRef.value.setCheckedNodes(data)
			treeRef.value.setCheckedKeys(data, false)
		}
	},
)

const setMenu = async () => {
	try {
		await addMenuAuthorityApi({
			authorityId: props.id,
			menus: treeRef.value.getCheckedNodes(),
		})
		ElMessage.success('配置成功')
		emit('update:visible', false)
		adminStore.menu = await adminStore.setMenu()
	} catch (err) {
		throw new Error(err)
	}
}

onMounted(async () => {
	let res = await getBaseMenuTreeApi()
	dataSource.value = res.menus
})
</script>

<style scoped>
.content {
	display: flex;
	justify-content: space-between;
	align-items: flex-start;
}
</style>
